package cn.seventree.file.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.seventree.file.entry.FileConfig;
import cn.seventree.file.service.EntryService;
import cn.seventree.file.util.FileHashUtil;
import cn.seventree.file.util.SimpleDirectoryVisitorImpl;

/**
 * 
 * @Description 根据目录下文件生成相应校验文件（用于文件的校验）
 * @author meikehuan
 * @date 2016年7月12日 上午9:14:47
 * @since 1.0.0
 */
@Service("entryService")
public class EntryServiceImpl implements EntryService {
	
	static private Logger logger = LoggerFactory.getLogger(EntryServiceImpl.class);
	
	@Autowired
	private FileConfig fileConfig;
	
	/**
	 * 初始化
	 * 
	 * @param args
	 * @throws IOException
	 */
	@Override
	public void init() {

		String path = fileConfig.getPath();
		String outPaht = fileConfig.getOutPath();

		List<File> list;
		try {
			list = getFileSort(path);

			List<String> hashList = new ArrayList<>();

			for (File file : list) {
				hashList.add(FileHashUtil.calculateFileHash(file.toPath()));
			}
			createFile(hashList, outPaht);
		} catch (IOException e) {
			logger.error("init error:",e);
		}
	}

	/**
	 * 获取目录下所有文件(按时间排序)
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 */
	private static List<File> getFileSort(String path) throws IOException {

		SimpleDirectoryVisitorImpl directoryVisitorImpl = new SimpleDirectoryVisitorImpl();
		Path rootpath = Paths.get(path);
		Files.walkFileTree(rootpath, directoryVisitorImpl);
		List<File> list = directoryVisitorImpl.getList();
		if (list != null && list.size() > 0) {
			Collections.sort(list, new Comparator<File>() {
				public int compare(File file, File newFile) {
					if (file.lastModified() < newFile.lastModified()) {
						return 1;
					} else if (file.lastModified() == newFile.lastModified()) {
						return 0;
					} else {
						return -1;
					}
				}
			});

		}
		return list;
	}

	/**
	 * 
	 * @Description 根据输出路径和输出参数，输出文件
	 */
	private static void createFile(List<String> outList, String outPath) {
		OutputStream fOut = null;
		try {
			fOut = new FileOutputStream(new File(outPath));
		} catch (FileNotFoundException e) {
			logger.error("createFile error",e);
		}
		for (String Str : outList) {
			try {
				fOut.write((Str + "\n").getBytes());
			} catch (IOException e) {
				logger.error("createFile error",e);
			}

		}
		if (fOut != null) {
			try {
				fOut.close();
			} catch (IOException e) {
				logger.error("createFile to close error",e);
			}
		}
	}

}
